package com.ehotting.mqbd.core.service;

import com.ehotting.eaf.core.StringHelper;
import com.ehotting.eaf.redis.service.RedisService;
import com.ehotting.mqbd.api.MQDBConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.concurrent.TimeUnit;

@Component
public class AgentRefConsumerService {

    private TimeUnit TIME_UNIT = TimeUnit.DAYS;
    private Long TIME_OUT = 10L;

    @Autowired
    private RedisService redisService;

    public void deleteConsumerIpByAgentId(String agentId){
        redisService.delete(MQDBConstants.AGENT_REF_CONSUMER + agentId);
    }


    public String getConsumerIpByAgentId(String agentId){
        String consumerIp = redisService.get(MQDBConstants.AGENT_REF_CONSUMER + agentId);
        return consumerIp;
    }

    public Collection<String> findAllAgentIdList(){
        Collection<String> agentIds = redisService.keys(MQDBConstants.AGENT_REF_CONSUMER + "*");
        return agentIds;
    }

    public void setConsumerIpAndAgentId(String agentId,String consumerIp){
        if(StringHelper.isBlank(agentId)){
            agentId= "default";
        }
        String key = MQDBConstants.AGENT_REF_CONSUMER + agentId;
        redisService.set(key,consumerIp, TIME_OUT,TIME_UNIT);
    }

    public void deleteAllAgentByConsumerIp(String ip){
        Collection<String> agentIds = findAllAgentIdList();
        for(String agentId : agentIds){
            String consumerIp = getConsumerIpByAgentId( agentId);
            if(ip.equals(consumerIp)){
                deleteConsumerIpByAgentId( agentId);
            }
        }
    }



}
